package com.esirong.whatime.ui.activity;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.esirong.dao.Task;
import com.esirong.whatime.R;
import com.esirong.whatime.model.ResultHandler;
import com.esirong.whatime.model.TaskModel;
import com.esirong.whatime.ui.widget.Anticlockwise;
import com.esirong.whatime.util.Logger;
import com.esirong.whatime.ui.adpater.TaskAdapter;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private TextView currentTaskTitle;
    private TextView currentTaskNote;
    private View mCurrentTaskInfo;
    private Anticlockwise mTaskTimingBoard;
    private ListView listView;
    private TaskAdapter taskAdapter;
    private Task currentTask;
    private List<Task> taskList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.ac_toolbar_for_action_bar_toolbar);
        setSupportActionBar(toolbar);
        initViews();
    }

    private void initViews() {
        mTaskTimingBoard = (Anticlockwise) findViewById(R.id.id_timer);
        currentTaskTitle = (TextView) findViewById(R.id.current_task_title);
        currentTaskNote = (TextView) findViewById(R.id.current_task_note);
        mCurrentTaskInfo = findViewById(R.id.current_task_info);
        findViewById(R.id.btn_main_start_or_pause).setOnClickListener(this);
        findViewById(R.id.btn_main_stop).setOnClickListener(this);
        findViewById(R.id.btn_main_delay).setOnClickListener(this);
        findViewById(R.id.btn_main_done).setOnClickListener(this);
        listView = (ListView) findViewById(R.id.list);
        mCurrentTaskInfo.setOnClickListener(this);
        taskAdapter = new TaskAdapter(this, taskList);
        listView.setAdapter(taskAdapter);

    }

    @Override
    protected void onResume() {
        super.onResume();
        showTask();
    }

    private void addTask() {
        taskAdapter.appendToList(taskList);
    }

    private void initTimer(Task info) {
        //初始化时间25分钟
        mTaskTimingBoard.initTime(25, 0);
        mTaskTimingBoard.setOnTimeCompleteListener(new Anticlockwise.OnTimeCompleteListener() {
            @Override
            public void onTimeComplete() {
                //计时完成
            }
        });
    }

    private void startTimer() {
        mTaskTimingBoard.startTimer();

    }

    private void showTask() {
        //显示
        TaskModel.getCurrentTask(this, new ResultHandler<Task>() {
            @Override
            public void onSuccess(Task result) {
                Logger.d(TAG, "获取数据成功");
                setCurrentTaskInfo(result);
            }

            @Override
            public boolean onFailed(int code) {
                Logger.e(TAG, "获取数据失败");
                return false;
            }
        });

    }

    private void setCurrentTaskInfo(Task info) {
        currentTaskTitle.setText(info.getTitle());
        currentTaskNote.setText(info.getNote());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.current_task_info:
                //TODO 尝试开始一个新的任务的task
                attemptStartNewTask();
                break;
            case R.id.btn_main_start_or_pause:
                attemptStartTheTask();
                break;
            case R.id.btn_main_stop:
                pauseTheTask();
                break;
            case R.id.btn_main_delay:
                attemptDelayTask();
                break;
            case R.id.btn_main_done:
                saveTheTask();
                break;
            default:
                break;
        }
    }

    /**
     * 任务延时，把任务的所需要的完成时增加。
     */
    private void attemptDelayTask() {

    }

    /**
     * 尝试开始任务（如果这个任被暂停的，则继续进行，如果这个任务还没有开始的，则开始一个新的任务）
     */
    private void attemptStartTheTask() {
        if (mTaskTimingBoard.isTimerPause()) {
            mTaskTimingBoard.resumeTimer();
        } else if (mTaskTimingBoard.isTimerComplete()) {
            attemptStartNewTask();
        }
    }

    /**
     * 停止任务 （如果这个任务仍在运行的，停止它，如果这个任务是暂停的，停止它）
     */
    private void pauseTheTask() {
        mTaskTimingBoard.pauseTimer();
    }

    /**
     * 完成任务，保存记录 停止这任务，并保存它完成的数据等情况
     */
    private void saveTheTask() {
        mTaskTimingBoard.stopTimer();
        currentTask.setTitle("done");
        taskAdapter.notifyDataSetChanged();
    }

    /**
     * 尝试开始一个新的任务
     */
    private void attemptStartNewTask() {
        currentTask = createNewTask();
        startTimer();

    }

    /**
     * 创建一个新的任务
     */
    private Task createNewTask() {
        currentTask = createANewTask();
        taskAdapter.appendToTopList(currentTask);
        setCurrentTaskInfo(currentTask);
        initTimer(currentTask);
        return currentTask;
    }

    private Task createANewTask() {
        currentTask = new Task();
        currentTask.setStart_at(System.currentTimeMillis());
        currentTask.setTitle("new Task");
        currentTask.setNote("new Task:" + System.currentTimeMillis());
        return currentTask;
    }

}
